<template>
	<view class="page">
		<u-sticky>
			<view>
				<view class="search_view flex align-center">
					<view class="city-serach flex align-center">
						<view class="search_city">{{city_name}}</view>
						<view class="search-input flex align-center">
							<input :value="serachCity" @input="keyInput" placeholder="输入机场/车站/商圈等"
								class="city-serach-input" />
							<image class="search-img" :src='STATIC_URL+"81.png"' mode="aspectFill"></image>
						</view>
					</view>
					<view class="back_text" @tap.stop="cleanInput">取消</view>
				</view>
				<view class="locate_info">
					<view class="locate_info_title">
						<view>当前位置</view>
					</view>
					<view class="locate_info_authorize flex">
						<view class="flex" style="flex: 7.9;" @tap.stop="isBack">
							<image class="locate_info_address_icon" :src='STATIC_URL+"79.png"'></image>
							<template v-if="!is_again">
								<view class="locate_info_text">定位中</view>
							</template>
							<template v-else>
								<view class="locate_info_text">{{cityInfo ? cityInfo.cityAddress : '定位中'}}</view>
							</template>
						</view>
						<view style="flex: 2.1;text-align: right;" @tap.stop="alignLocation">
							<text>重新定位</text>
							<u-icon name="reload"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</u-sticky>
		
		<view class="locate_info" style="padding: 0 30rpx 30rpx;" v-if="!searchStatus">
			<template v-if="airportList.length > 0">
				<view class="pois_title flex align-center" @tap.stop="seePoi(1)">
					<image :src='STATIC_URL+"144.png"' mode="aspectFill"></image>
					<view>机场</view>
					<view class="pois_icon">
						<u-icon v-if="!show1" name="arrow-down" size="24" color="#999"></u-icon>
						<u-icon v-else name="arrow-up" size="24" color="#999"></u-icon>
					</view>
				</view>
				<view class="pois_list">
					<view class="pois_item" v-for="(item, index) in airportListShow" :key="index" @click="selectDistricts(item)">{{item.name}}</view>
				</view>
			</template>
			<template v-if="trainList.length > 0">
				<view class="pois_title flex align-center" @tap.stop="seePoi(2)">
					<image :src='STATIC_URL+"145.png"' mode="aspectFill"></image>
					<view>火车站</view>
					<view class="pois_icon">
						<u-icon v-if="!show2" name="arrow-down" size="24" color="#999"></u-icon>
						<u-icon v-else name="arrow-up" size="24" color="#999"></u-icon>
					</view>
				</view>
				<view class="pois_list">
					<view class="pois_item" v-for="(item, index) in trainListShow" :key="index" @click="selectDistricts(item)">{{item.name}}</view>
				</view>
			</template>
			<template v-if="scenicSpot.length > 0">
				<view class="pois_title flex align-center" @tap.stop="seePoi(3)">
					<image :src='STATIC_URL+"146.png"' mode="aspectFill"></image>
					<view>热门景点</view>
					<view class="pois_icon">
						<u-icon v-if="!show3" name="arrow-down" size="24" color="#999"></u-icon>
						<u-icon v-else name="arrow-up" size="24" color="#999"></u-icon>
					</view>
				</view>
				<view class="pois_list">
					<view class="pois_item" v-for="(item, index) in scenicSpotShow" :key="index" @click="selectDistricts(item)">{{item.name}}</view>
				</view>
			</template>
			<template v-if="mallList.length > 0">
				<view class="pois_title flex align-center" @tap.stop="seePoi(4)">
					<image :src='STATIC_URL+"147.png"' mode="aspectFill"></image>
					<view>商圈</view>
					<view class="pois_icon">
						<u-icon v-if="!show4" name="arrow-down" size="24" color="#999"></u-icon>
						<u-icon v-else name="arrow-up" size="24" color="#999"></u-icon>
					</view>
				</view>
				<view class="pois_list">
					<view class="pois_item" v-for="(item, index) in mallListShow" :key="index" @click="selectDistricts(item)">{{item.name}}</view>
				</view>
			</template>
			<template v-if="busStation.length > 0">
				<view class="pois_title flex align-center" @tap.stop="seePoi(5)">
					<image :src='STATIC_URL+"148.png"' mode="aspectFill"></image>
					<view>汽车站</view>
					<view class="pois_icon">
						<u-icon v-if="!show5" name="arrow-down" size="24" color="#999"></u-icon>
						<u-icon v-else name="arrow-up" size="24" color="#999"></u-icon>
					</view>
				</view>
				<view class="pois_list">
					<view class="pois_item" v-for="(item, index) in busStationShow" :key="index" @click="selectDistricts(item)">{{item.name}}</view>
				</view>
			</template>
		</view>
		<template v-if="searchStatus">
			<view class="locate_info" v-if="searchDatas.length > 0">
				<view class="locate_info_title">
					<view>选择位置</view>
				</view>
			</view>
			<view class="locate_info">
				<view class="loading_css" v-if="is_search">
					<u-loading size="36" color="#FC5B03"></u-loading>
					<view>加载中</view>
				</view>
				<view class="locate_info_list" v-if="!is_search && searchDatas.length > 0">
					<view class="locate_info_item" v-for="(item, index) in searchDatas" :key="index"
						@click="selectDistricts(item)">
						{{item.name}}
					</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				scrollview: "A",
				cityList: [],
				activeIndex: "A",
				touchmove: false,
				serachCity: "",
				hostCityList: [],
				cityInfo: "",
				is_again: false,
				searchDatas: [],
				cityName: "", // 选择的城市
				city_name: "",
				is_search: false,
				lastSearchLength: 0,
				currentLength: 0,
				poiList: [],
				trainList: [],  // 火车站
				busStation: [],  // 汽车站
				airportList: [],  // 机场
				mallList: [],  // 商圈
				scenicSpot: [],  // 旅游景点
				searchStatus: false,  // 展示默认的位置列表
				defaultCount: 4,
				show1: false,
				show2: false,
				show3: false,
				show4: false,
				show5: false,
			};
		},
		watch: {

		},
		computed: {
			airportListShow() {
				return this.show1 ? this.airportList : this.airportList.slice(0, this.defaultCount);
			},
			trainListShow() {
				return this.show2 ? this.trainList : this.trainList.slice(0, this.defaultCount);
			},
			busStationShow() {
				return this.show5 ? this.busStation : this.busStation.slice(0, this.defaultCount);
			},
			scenicSpotShow() {
				return this.show3 ? this.scenicSpot : this.scenicSpot.slice(0, this.defaultCount);
			},
			mallListShow() {
				return this.show4 ? this.mallList : this.mallList.slice(0, this.defaultCount);
			},
		},
		onLoad(options) {
			let {
				cityName
			} = options;
			if (cityName !== undefined) this.cityName = cityName;
			if (uni.getStorageSync('city')) {
				this.cityInfo = uni.getStorageSync('city');
				this.filterCity();
				this.is_again = true;
				console.log(this.cityInfo);
			}
		},
		methods: {
			// 获取当前城市的poi数据
			getCityPoi() {
				let pois = [];
				if (uni.getStorageSync('pois')) {
					pois = uni.getStorageSync('pois');
					let poisIndex = pois.findIndex(e => e.city == this.city_name);
					if (poisIndex != -1) {
						this.trainList = pois[poisIndex].trainList;
						this.busStation = pois[poisIndex].busStation;
						this.airportList = pois[poisIndex].airportList;
						this.mallList = pois[poisIndex].mallList;
						this.scenicSpot = pois[poisIndex].scenicSpot;
					} else {
						this.requestCityPois();
					}
				} else {
					this.requestCityPois();
				}
			},
			requestCityPois() {
				let _this = this;
				_this.$api.post(global.apiUrls.cityData, {
					city_name: _this.city_name
				}).then(resData => {
					console.log(resData);
					if (resData.data.code == 1) {
						if (resData.data.data) {
							let pois = resData.data.data;
							let poisIndex = pois.findIndex(e => e.city == _this.city_name);
							_this.trainList = pois[poisIndex].trainList;
							_this.busStation = pois[poisIndex].busStation;
							_this.airportList = pois[poisIndex].airportList;
							_this.mallList = pois[poisIndex].mallList;
							_this.scenicSpot = pois[poisIndex].scenicSpot;
							uni.setStorageSync('pois', pois);
						} else {
							uni.request({
								url: 'https://restapi.amap.com/v3/place/text',
								data: {
									key: global.ampKey,
									types: '150104|150200',
									// types: '飞机场|火车站',
									city: _this.city_name,
									citylimit: true,
									offset: 25,
									page: 1
								},
								success: (res) => {
									console.log(res);
									if (res.data.status === '1') {
										uni.request({
											url: 'https://restapi.amap.com/v3/place/text',
											data: {
												key: global.ampKey,
												types: '150400|110203|060101',
												city: _this.city_name,
												citylimit: true,
												offset: 25,
												page: 1
											},
											success: (result) => {
												if (result.data.status === '1') {
													if (res.data.pois.length > 0) {
														res.data.pois.forEach((item,index) => {
															if (item.typecode.includes('150104')) {
																_this.airportList.push(item);
															} else if (item.typecode.includes('150200')) {
																_this.trainList.push(item);
															}
														})
													}
													if (result.data.pois.length > 0) {
														result.data.pois.forEach((item,index) => {
															if (item.typecode.includes('060101')) {
																_this.mallList.push(item);
															} else if (item.typecode.includes('110203')) {
																_this.scenicSpot.push(item);
															} else if (item.typecode.includes('150400')) {
																_this.busStation.push(item);
															}
														})
													}
													let pois = [];
													if (uni.getStorageSync('pois')) {
														pois = uni.getStorageSync('pois');
													}
													pois.push({
														city: _this.city_name,
														trainList: _this.trainList,
														busStation: _this.busStation,
														airportList: _this.airportList,
														mallList: _this.mallList,
														scenicSpot: _this.scenicSpot
													})
													uni.setStorageSync('pois', pois);
													_this.$api.post(global.apiUrls.cityData, {
														city_name: _this.city_name,
														city_data: JSON.stringify(pois)
													}).then(cityRes => {
														console.log(cityRes)
													})
												}
											},
											fail: (err) => {
												console.log(err);
											}
										})
									}
								},
								fail: (err) => {
									console.log(err);
								}
							});
						}
					} else {
						_this.$message.info(resData.data.info);
					}
				})
				
			},
			seePoi(type) {
				if (type == 1) {
					this.show1 = !this.show1;
				} else if (type == 2) {
					this.show2 = !this.show2;
				} else if (type == 3) {
					this.show3 = !this.show3;
				} else if (type == 4) {
					this.show4 = !this.show4;
				} else if (type == 5) {
					this.show5 = !this.show5;
				}
			},
			
			/**
			 * @desc 监听输入框的值
			 */
			keyInput(event) {
				let _this = this;
				_this.serachCity = event.detail.value;
				_this.currentLength = _this.serachCity.length;

				if (_this.currentLength > _this.lastSearchLength && _this.currentLength >= 2) {
					_this.lastSearchLength = _this.currentLength;
					_this.searchStatus = true;
					_this.is_search = true;
					uni.$u.debounce(this.getSearchData, 2000)
				} else if (_this.currentLength < _this.lastSearchLength) {
					// 输入长度减少时更新记录
					_this.lastSearchLength = _this.currentLength;
				}
			},
			getSearchData() {
				let _this = this;
				uni.request({
					url: 'https://restapi.amap.com/v3/place/text',
					data: {
						key: global.ampKey,
						keywords: _this.serachCity,
						city: _this.city_name,
						citylimit: true,
						offset: 25,
						page: 1
					},
					success: (res) => {
						// console.log(res);
						if (res.data.status === '1') {
							_this.searchDatas = res.data.pois; // 保存搜索结果
							_this.is_search = false;
						} else {
							_this.$message.info('搜索失败，请稍后重试');
						}
					},
					fail: (err) => {
						_this.$message.info('搜索失败，请稍后重试');
					}
				});
			},
			selectDistricts(item) {
				console.log('选择的位置', item);
				let _this = this;
				uni.request({
					url: 'https://restapi.amap.com/v3/config/district?keywords=' + _this.city_name +
						'&key=' + global.ampKey, //仅为示例，并非真实接口地址。
					header: {
						'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
					},
					success: (res) => {
						console.log('123', res);
						if (res.data.status == '1') {
							let lngArr = item.location.split(',');
							let obj = "";
							if (res.data.districts.length > 1) {
								let arr = (res.data.districts.filter(e => e.name == _this.city_name))
								if (arr.length > 0) {
									obj = arr[0];
								} else {
									obj = res.data.districts[0];
								}
							} else {
								obj = res.data.districts[0];
							}

							let cityInfo = {
								citycode: obj.citycode,
								city: obj.name.slice(0, -1),
								city_districts: item.name,
								cityAddress: obj.name + item.name,
								lng: Number(lngArr[0]),
								lat: Number(lngArr[1])
							}
							console.log('保存的位置信息', cityInfo);
							uni.setStorageSync('city', cityInfo);
							uni.$emit('selectDistricts'); // 刷新车型列表
							uni.navigateBack();
						} else {
							_this.$message.info('获取地理位置信息失败');
						}

					},
					fail: (error) => {
						// console.log(error)
						_this.$message.info('获取地理位置信息失败');
					}
				});
			},
			alignLocation() {
				let _this = this;
				_this.is_again = false;
				_this.serachCity = "";
				_this.searchDatas = [];
				uni.getSetting({
					success(res) {
						console.log(res);
						let locationStatus = true;
						// #ifdef MP-ALIPAY
						locationStatus = res.authSetting['location'];
						// #endif

						// #ifndef MP-ALIPAY
						locationStatus = res.authSetting['scope.userLocation'];
						// #endif

						if (locationStatus) {
							// 用户已经授权
							console.log('用户已授权定位');
							uni.getLocation({
								type: 'gcj02',
								success: function(res) {
									console.log(res);
									let location = res.longitude + ',' + res.latitude;
									_this.getAddressInfo(location, res.longitude, res.latitude);
								},
								fail: function(error) {
									// console.log(error);
									_this.$message.info('获取地理位置信息失败');
								}
							});
						} else {
							// 用户未授权，可以引导用户去授权
							console.log('用户未授权定位');
							uni.openSetting({
								success(res) {},
								fail(err) {
									console.log(err);
								}
							});
						}
					}
				});

			},
			// 逆地理编码 根据经纬度获取到城市信息
			getAddressInfo(location, lng, lat) {
				let _this = this;
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?location=' + location +
						'&key=' + global.ampKey, //仅为示例，并非真实接口地址。
					header: {
						'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
					},
					success: (res) => {
						// console.log('456', res);
						if (res.data.status == '1') {
							let districtsIndex = res.data.regeocode.formatted_address.indexOf(res.data
								.regeocode.addressComponent.city);
							if (districtsIndex != -1) {
								districtsIndex = districtsIndex + res.data.regeocode.addressComponent.city
									.length;
							}
							let city_districts = res.data.regeocode.formatted_address.slice(districtsIndex, res
								.data.regeocode.formatted_address.length);
							let cityInfo = {
								citycode: res.data.regeocode.addressComponent.citycode,
								city: res.data.regeocode.addressComponent.city.slice(0, -1),
								city_districts: city_districts,
								cityAddress: res.data.regeocode.addressComponent.city + city_districts,
								lng: Number(lng),
								lat: Number(lat)
							}
							uni.setStorageSync('city', cityInfo);
							_this.cityInfo = cityInfo;
							_this.cityName = "";
							_this.filterCity();
							_this.is_again = true;
							_this.searchStatus = false;
						} else {
							_this.$message.info('获取地理位置信息失败');
						}

					},
					fail: (error) => {
						// console.log(error)
						_this.$message.info('获取地理位置信息失败');
					}
				});
			},
			filterCity() {
				let city_name;
				if (this.cityName) {
					city_name = this.cityName;
				} else {
					city_name = this.cityInfo.city + '市';
				}
				if (city_name.length > 3) {
					city_name = city_name.substring(0, 3) + '...';
				}
				this.city_name = city_name;
				this.getCityPoi();
			},
			isBack() {
				uni.navigateBack();
			},
			cleanInput() {
				this.serachCity = "";
				this.lastSearchLength = 0;
				this.searchStatus = false;
			}
		},
	};
</script>

<style lang="scss" scoped>
	.page {
		height: 100vh;
		background: #fff;
	}

	.search_view {
		background: #fff;
		padding-left: 28rpx;
		position: relative;
		z-index: 10;
	}

	.city-serach {
		background: #F7F7F7;
		border-radius: 40rpx;
		flex: 1;

		.search_city {
			padding: 0 16rpx;
			font-size: 26rpx;
			color: #666666;
			border-right: 1px solid #eee;
			display: -webkit-box;
		}

		.search-input {
			flex: 1;
			position: relative;

			.search-img {
				position: absolute;
				top: 50%;
				left: 12rpx;
				transform: translateY(-50%);
				width: 28rpx;
				height: 28rpx;
			}
		}

		&-input {
			height: 60rpx;
			font-weight: 400;
			font-size: 26rpx;
			color: #999999;
			padding: 0 24rpx 0 50rpx;
			background: #F7F7F7;
		}
	}

	.back_text {
		font-size: 26rpx;
		margin-left: 24rpx;
		margin-right: 30rpx;
	}

	.locate_info {
		background: #fff;
		padding: 30rpx 30rpx 0;

		&_title {
			font-size: 30rpx;
			// color: #666666;
			position: relative;
		}

		&_icon {
			background: #FC5B03;
			width: 6rpx;
			height: 24rpx;
			border-radius: 3rpx;
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
		}

		&_authorize {
			padding: 24rpx 0;
			font-size: 26rpx;
		}

		&_item {
			padding: 24rpx 30rpx;
			font-size: 26rpx;
			border-bottom: 1px solid #F7F7F7;
		}

		&_item:last-child {
			border-bottom: 0;
		}

		&_address_icon {
			width: 30rpx;
			height: 30rpx;
			margin-right: 10rpx;
			transform: translateY(3rpx);
		}

		&_text {
			width: calc(100% - 55rpx);
		}
		.pois_title {
			font-size: 30rpx;
			// color: #666666;
			margin-top: 32rpx;
			image {
				width: 32rpx;
				height: 32rpx;
				margin-right: 24rpx;
			}
			.pois_icon {
				margin-left: auto;
			}
		}
		.pois_list {
			overflow: hidden;
			.pois_item {
				float: left;
				margin: 20rpx 20rpx 0 0;
				font-size: 24rpx;
				background: #F7F7F7;
				padding: 8rpx 12rpx;
				border-radius: 8rpx;
			}
		}
	}

	.t-index-address {
		height: 100%;
		background: #fff;

		&__scroll-view {
			width: 100%;
			height: 100%;
			max-height: 100vh;
		}

		&__anchor {
			padding: 15rpx 30rpx;
			width: 100%;
			font-size: 28rpx;
			font-weight: 500;
			color: #606266;
			background-color: rgb(245, 245, 245);
		}

		&__list {
			padding: 0 70rpx 0 30rpx;
		}

		&__cell {
			height: 70rpx;
			line-height: 70rpx;
			border-bottom: 1rpx solid #f2f2f2;
			font-size: 24rpx;

			&:last-child {
				border: none;
			}
		}

		&__sidebar {
			position: fixed;
			top: 60%;
			right: 0;
			transform: translateY(-50%);
			z-index: 99;
		}

		&__index {
			padding: 10rpx 20rpx;
			font-size: 22rpx;
			font-weight: 500;
			line-height: 1;
		}

		&__alert {
			position: fixed;
			top: 50%;
			right: 90rpx;
			z-index: 99;
			margin-top: -60rpx;
			width: 120rpx;
			height: 120rpx;
			font-size: 50rpx;
			color: #fff;
			border-radius: 24rpx;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>